﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Dict.Blo;
using Dict.DataModel;

namespace UI
{
    public enum RemoteType
    {
        LevelUp = 0,
        Talent = 1,
        Train = 2,
        BreakThrough = 3
    }

    public class CharacterRemotePage : Page
    {
        public GameObject heroPosition;
        GameObject heroObj;
        public ItemSelect topLeft;//左上角的（升级，天赋，训练，突破）

        //四个tab页
        public List<GameObject> rightPages;

        private RemoteType lastRemoteType;
        private RemoteType remoteType;
        private string guid = "";
        private UIHero hero;

        protected override void DoOpen()
        {
            gameObject.GetComponent<PageTweener>().Play();

            guid = options["guid"];
            hero = StaticData.playerData.InstPlayerData.GetUIHero(guid);
            remoteType = (RemoteType)(int.Parse(options["tab"]));

            if (hero.heroData.heroClass == (int)HeroClass.Main_Actor_Man || hero.heroData.heroClass == (int)HeroClass.Main_Actor_Woman)
            {
                topLeft.UpdateMode(false);
                if(remoteType == RemoteType.LevelUp)
                    remoteType = RemoteType.Talent;
            }
            else
            {
                topLeft.UpdateMode(true);
            }

            OpenPage(remoteType);

            StartCoroutine(_InitHero());
        }

        protected override void DoClose()
        {
            base.DoClose();

            if(heroObj != null)
            {
                ModelRenderKit mrk = heroObj.GetComponent<ModelRenderKit>();
                mrk.SwitchLod(true);
                mrk.UnloadWeapons();
                isWeaponLoaded = false;
                ResourceLoader.GetInstance().modelLoader.UnloadModel(heroObj, hero.heroData.resName);
            }

            rightPages[(int)RemoteType.LevelUp].GetComponent<LevelUpPage>().DestroyParticlesImdt();
        }

        /// <summary>
        /// 升级
        /// </summary>
        public void OnLevelUpClick()
        {
            ClearLevelUpPageParticle(remoteType);
            remoteType = RemoteType.LevelUp;
            OpenPage(remoteType);
        }

        /// <summary>
        /// 天赋
        /// </summary>
        public void OnTalentClick()
        {
            ClearLevelUpPageParticle(remoteType);
            remoteType = RemoteType.Talent;
            OpenPage(remoteType);
        }

        /// <summary>
        /// 训练
        /// </summary>
        public void OnTrainClick()
        {
            //检测等级
            if (StaticData.playerData.level < Dict.DictDataManager.Instance.tableGameConfigureDao.currentData.HeroTrainLevel)
            {
                BoxManager.CreatePopupTextBox(string.Format(TableTextBlo.GetText("hero_train_level_limit"), Dict.DictDataManager.Instance.tableGameConfigureDao.currentData.HeroTrainLevel));
                return;
            }
            ClearLevelUpPageParticle(remoteType);
            remoteType = RemoteType.Train;
            OpenPage(remoteType);
        }

        /// <summary>
        /// 突破
        /// </summary>
        public void OnBreakThroughClick()
        {
            //检测等级
            if (StaticData.playerData.level < Dict.DictDataManager.Instance.tableGameConfigureDao.currentData.HeroBreachedLevel)
            {
                BoxManager.CreatePopupTextBox(string.Format(TableTextBlo.GetText("hero_breach_level_limit"), Dict.DictDataManager.Instance.tableGameConfigureDao.currentData.HeroBreachedLevel));
                return;
            }
            ClearLevelUpPageParticle(remoteType);
            remoteType = RemoteType.BreakThrough;
            OpenPage(remoteType);
        }

        void ClearLevelUpPageParticle(RemoteType type)
        {
            if(type == RemoteType.LevelUp)
                rightPages[(int)RemoteType.LevelUp].GetComponent<LevelUpPage>().DestroyParticlesImdt();
        }

        /// <summary>
        /// 判断打开哪个面板
        /// </summary>
        /// <param name="type"></param>
        private void OpenPage(RemoteType type)
        {
            if(type == RemoteType.Train && StaticData.playerData.level < Dict.DictDataManager.Instance.tableGameConfigureDao.currentData.HeroTrainLevel)
            {
                type = RemoteType.LevelUp;
                BoxManager.CreatePopupTextBox(string.Format(TableTextBlo.GetText("hero_train_level_limit"), Dict.DictDataManager.Instance.tableGameConfigureDao.currentData.HeroTrainLevel));
            }

            if (lastRemoteType != type)
            {
                rightPages[(int)lastRemoteType].SetActive(false);
            }
            remoteType = type;
            lastRemoteType = remoteType;
            rightPages[(int)type].SetActive(true);

            Vector3 pos = heroPosition.transform.localPosition;
            switch (type)
            {
                case RemoteType.LevelUp:
                    {
                        ShowHeroModel();
                        heroPosition.transform.localPosition = new Vector3(-160, pos.y, pos.z);
                        topLeft.SelectLevel();
                        rightPages[(int)type].GetComponent<LevelUpPage>().SetHero(guid);
                    }
                    break;
                case RemoteType.Talent:
                    {
                        HideHeroModel();
                        topLeft.SelectTalent();
                        rightPages[(int)type].GetComponent<TalentPage>().SetHero(guid);
                    }
                    break;
                case RemoteType.Train:
                    {
                        ShowHeroModel();
                        heroPosition.transform.localPosition = new Vector3(-87, pos.y, pos.z);
                        topLeft.SelectTrain();
                        rightPages[(int)type].GetComponent<TrainPage>().SetHero(guid);
                    }
                    break;
                case RemoteType.BreakThrough:
                    {
                        ShowHeroModel();
                        heroPosition.transform.localPosition = new Vector3(-160, pos.y, pos.z);
                        topLeft.SelectBreakThrough();
                        rightPages[(int)type].GetComponent<BreachPage>().SetHero(guid);
                    }
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 初始化英雄模型
        /// </summary>
        IEnumerator _InitHero() 
        {
            yield return new WaitForSeconds(0.5f);

            isWeaponLoaded = false;
            float scale = (float)hero.heroData.ScaleFactor;
            yield return StartCoroutine(ResourceLoader.GetInstance().modelLoader.LoadModel(hero.heroData.resName, (asset) => {
                GameObject heroAni = asset as GameObject;
                if (heroAni != null) {
                    heroAni.transform.SetParent(heroPosition.transform);
                    heroAni.transform.localPosition = Vector3.zero;
                    heroAni.transform.localScale = Vector3.one * scale;
                    heroAni.transform.localEulerAngles = Vector3.zero;
                    heroAni.GetComponent<LegacyAnimation>().Play(AniName.STAND, WrapMode.Loop);
                    heroObj = heroAni;
                }
            }));

            if (heroObj != null)
            {
                CommonMethod.ChangeLayer(heroObj.transform, heroPosition.layer);
                if (!isWeaponLoaded)
                {
                    StartCoroutine(_InitModelWeapon());
                }
            }
        }

        IEnumerator _InitModelWeapon()
        {
            if (heroObj == null)
            {
                yield break;
            }
            while (!heroObj.activeInHierarchy)
            {
                yield break;
            }

            string weaponid = "";
            if(hero.owner != null && hero.owner.equipments[0] != null)
            {
                weaponid = hero.owner.equipments[0].equipId;
            }

            ModelRenderKit mrk = heroObj.GetComponent<ModelRenderKit>();
            yield return StartCoroutine(mrk.LoadWeapons(hero.heroId, weaponid));
            CommonMethod.ChangeLayer(heroObj.transform, heroPosition.layer);
            mrk.SwitchLod(false);
            heroObj.SetActive(true);
            isWeaponLoaded = true;
        }

        private bool isWeaponLoaded = false;

        public void ShowHeroModel() {
            heroPosition.SetActive(true);
            if (heroObj != null) {
                heroObj.GetComponent<LegacyAnimation>().Play(AniName.STAND, WrapMode.Loop);
            }
        }

        public void HideHeroModel() {
            heroPosition.SetActive(false);
        }

        public override void OnCoverPageOpen()
        {
            base.OnCoverPageOpen();
            rightPages[(int)RemoteType.LevelUp].GetComponent<LevelUpPage>().DestroyParticlesImdt();
            rightPages[(int)RemoteType.BreakThrough].GetComponent<BreachPage>().SetParticleRenderOrder(false);
        }

        public override void OnCoverPageRemove()
        {
            base.OnCoverPageRemove();
            rightPages[(int)RemoteType.BreakThrough].GetComponent<BreachPage>().SetParticleRenderOrder(true);
        }

    }
}
